package com.heima.app.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.app.mapper.ApUserLoginMapper;
import com.heima.app.service.ApUserLoginService;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
 * @projectName: heima-leadnews
 * @package: com.heima.app.service.impl
 * @className: ApUserLoginServiceImpl
 * @author: 躺着认真玩
 * @description: app端用户登录服务层
 * @date: 2025/5/14 22:54
 * @version: 1.0
 */
@Service
public class ApUserLoginServiceImpl extends ServiceImpl<ApUserLoginMapper,ApUser> implements ApUserLoginService{
    @Override
    public ResponseResult login(LoginDto dto) {
        String password = dto.getPassword();
        String phone = dto.getPhone();
        if (!StrUtil.isBlank(password) && !StrUtil.isBlank(phone)) {
            // 1`查询电话号码  查询用户
            ApUser apUser = this.lambdaQuery().eq(ApUser::getPhone, phone).one();
            // 2.判断是否存在 并进行密码校验
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
            }
            String salt = apUser.getSalt();
            String md5 = DigestUtil.md5Hex(salt + dto.getPassword());
            if (!StrUtil.equals(md5,apUser.getPassword())) {
                throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            // 生成token进行返回
            String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",token);
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",AppJwtUtil.getToken(0L));
        return ResponseResult.okResult(map);
    }
}
